package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material.icons.outlined.ThumbUp
import androidx.compose.material.icons.filled.Reply
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.components.SimpleAvatarImage
import com.sddnytsh.body_buildingsystem.components.DefaultAvatar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.MediaType.Companion.toMediaType
import com.google.gson.Gson
import java.io.IOException

// 评论点赞响应数据类
data class CommentLikeResponse(val success: Boolean, val message: String? = null)

// 评论点赞API函数
suspend fun toggleCommentLike(userId: Long, commentId: Long): CommentLikeResponse {
    return withContext(Dispatchers.IO) {
        val url = "${com.sddnytsh.body_buildingsystem.config.NetworkConfig.BASE_URL}/api/comment-like/toggle"

        val requestBody = mapOf(
            "userId" to userId,
            "commentId" to commentId
        )
        val jsonBody = Gson().toJson(requestBody)

        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
        val request = Request.Builder()
            .url(url)
            .post(jsonBody.toRequestBody("application/json".toMediaType()))
            .addHeader("Content-Type", "application/json")
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            val gson = Gson()
            gson.fromJson(responseBody, CommentLikeResponse::class.java)
        }
    }
}

@Composable
fun CommentItem(
    comment: Comment,
    onReplyClick: (Comment) -> Unit = {}
) {
    var isLiked by remember { mutableStateOf(comment.isLiked) }
    var likeCount by remember { mutableStateOf(comment.likeCount) }
    var lastClickTime by remember { mutableStateOf(0L) }

    Card(
        modifier = Modifier
            .fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            // 评论作者信息
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 评论头像
                if (comment.authorAvatar != null && comment.authorAvatar.isNotEmpty()) {
                    SimpleAvatarImage(
                        avatarUrl = comment.authorAvatar,
                        fallbackName = comment.author ?: "未知用户",
                        size = 36.dp
                    )
                } else {
                    DefaultAvatar(
                        name = comment.author ?: "未知用户",
                        size = 36.dp
                    )
                }
                Spacer(modifier = Modifier.width(8.dp))
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = comment.author ?: "匿名用户",
                        style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium)
                    )
                    Text(
                        text = comment.createdAt,
                        color = Color.Gray
                    )
                }

                // 操作按钮区域
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)
                ) {
                    // 回复按钮 - 只有一级评论才显示
                    if (comment.parentId == null) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .clickable { 
                                    val currentTime = System.currentTimeMillis()
                                    if (currentTime - lastClickTime > 500) { // 500ms 防抖
                                        lastClickTime = currentTime
                                        onReplyClick(comment)
                                    }
                                }
                                .padding(4.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Filled.Reply,
                                contentDescription = "回复",
                                tint = Color(0xFF4361EE),
                                modifier = Modifier.size(16.dp)
                            )
                            Spacer(modifier = Modifier.width(4.dp))
                            Text(
                                text = "回复",
                                color = Color(0xFF4361EE),
                                style = MaterialTheme.typography.bodySmall
                            )
                        }
                    }

                    // 点赞按钮 - 调用后端API
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier
                            .clickable {
                                // 调用后端API切换点赞状态
                                CoroutineScope(Dispatchers.IO).launch {
                                    try {
                                        val response: CommentLikeResponse = withContext<CommentLikeResponse>(Dispatchers.IO) {
                                            toggleCommentLike(comment.userId, comment.id)
                                        }
                                        if (response.success) {
                                            withContext(Dispatchers.Main) {
                                                isLiked = !isLiked
                                                likeCount = if (isLiked) likeCount + 1 else likeCount - 1
                                            }
                                        }
                                    } catch (e: Exception) {
                                        // 处理错误，暂时不更新UI
                                    }
                                }
                            }
                            .padding(4.dp) // 增加点击区域
                    ) {
                    Icon(
                        imageVector = if (isLiked) Icons.Filled.ThumbUp else Icons.Outlined.ThumbUp,
                        contentDescription = "点赞",
                        tint = if (isLiked) Color(0xFFF44336) else Color.Gray,
                        modifier = Modifier.size(16.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = "$likeCount",
                        color = if (isLiked) Color(0xFFF44336) else Color.Gray,
                        modifier = Modifier.widthIn(min = 20.dp) // 确保数字有足够空间
                    )
                }
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 评论内容
            Text(
                text = comment.content,
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.fillMaxWidth(),
                lineHeight = 20.sp
            )
        }
    }
}
